package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
)

//实体列表
type EntityDataQueryData struct {
    EntitySet string `db:"Fentity_set" json:"entity_set"`
    EntityDesc string `db:"Fdesc" json:"entity_desc"`
    EntityName string `db:"Fname" json:"entity_name"`
    EntityClass1 int `db:"Fclass1" json:"entity_class1"`
    EntityClass2 int `db:"Fclass2" json:"entity_class2"`
    EntityPreAttr string `db:"Fpre_attr" json:"pre_attr"`
    EntityPostAttr string `db:"Fpost_attr" json:"post_attr"`
}

type EntityDataQueryCgi struct {
	Common.CgiBase
	DbEntity []EntityDataQueryData
}

func (cgi *EntityDataQueryCgi)quertEntityDetail() (bool) {
	sql := "select Fentity_set,Fdesc,Fname,Fclass1,Fclass2,Fpre_attr,Fpost_attr from db_entity_set_data where Fname=?;"
	err := Databases.Db.Select(&cgi.DbEntity, sql, cgi.Input["name"])
	if err != nil {
		fmt.Println("exec failed, ", err)
		return false
	}
    return true
}

func (cgi *EntityDataQueryCgi)transformEntity() (string){
    str, _ := json.Marshal(cgi.DbEntity[0])
    str_res := string(str)
    return str_res
}

func (cgi *EntityDataQueryCgi)processParam(c *gin.Context) {
	cgi.Input["name"] = c.Query("name")
}

func EntityDataQuery(c *gin.Context) {
	defer func(){
		fmt.Println("开始处理异常")
		if err:=recover();err!=nil{
			fmt.Println("error:",err)
			c.JSON(http.StatusOK, gin.H{
		        "result": -1,
		        "msg":    err,
		        "data": "{}",
		    })
		}
	}()


	var cgi EntityDataQueryCgi
	cgi.Init(c)
	cgi.processParam(c)

	res := cgi.quertEntityDetail()
	if (!res) {
		panic("query fail")
		/*c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "query fail",
	        "data": "{}",
	    })
	    return*/
	}

	if len(cgi.DbEntity) < 1 {
		panic("no data")
		/*
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "no data",
	        "data": "{}",
	    })
		fmt.Println("no data")
		return*/
	}

	json_res := cgi.transformEntity()

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": json_res,
    })

}

